package com.ty.service.impl;

import com.ty.bean.ProductInquiry;
import com.ty.bean.UserInfo;
import com.ty.common.crud.BaseServiceImpl;
import com.ty.common.utils.Assert;
import com.ty.context.UserContext;
import com.ty.mapper.CustomerMapper;
import com.ty.mapper.ProductInquiryDetailMapper;
import com.ty.mapper.ProductInquiryMapper;
import com.ty.mapper.ProductQuoteMapper;
import com.ty.service.ProductInquiryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class ProductInquiryServiceImpl extends BaseServiceImpl<ProductInquiry, ProductInquiryMapper> implements ProductInquiryService {

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    ProductInquiryDetailMapper productInquiryDetailMapper;

    @Autowired
    ProductQuoteMapper productQuoteMapper;

    @Transactional
    @Override
    public int save(ProductInquiry entity) {
        //产生编码  CPXJ2025020001
        entity.setSn("CPXJ2025020001");

        //获取当前操作人信息
        UserInfo info = UserContext.get();
        entity.setSeller_id(info.getId());
        entity.setSeller_name(info.getUsername());
        UserContext.clear();

        //解决客户问题
        //判断客户是否传递
        if (entity.getCid() != 0) {
            //根据客户id查询联系人名称 和联系方式
            Map map = customerMapper.queryContact(entity.getCid());
            Object name = map.get("contactName");
            entity.setCustomer_contact_people(null == name ? "" : name.toString());
            Object mobile = map.get("mobile");
            entity.setCustomer_contact_number(null == mobile ? "" : mobile.toString());
        }

        //保存询价单
        int rs = super.save(entity);
        Assert.isZero(rs, "保存产品询价单失败");

        //保存明细
        if (null != entity.getProductInquiryDetails() && entity.getProductInquiryDetails().size() > 0) {
            rs = productInquiryDetailMapper.batchSave(entity.getId(), entity.getProductInquiryDetails());
            Assert.isZero(rs, "保存产品询价单明细失败");

            //遍历产品明细
            entity.getProductInquiryDetails().forEach(el -> {
                //根据产品id查询 对应供应商（经营该类型产品的供应商 ）
                List<Integer> list = baseMapper.querySupplierId(el.getProduct_id());
                if (null != list && list.size() > 0) {
                    //保存供应商报价信息
                    for (int i = 0, len = list.size(); i < len; i++) {
                        //保存 编码 用询价单编码+子编码  CPXJ20250001-01
                        String tmp = "CPXJ20250001-" + (i + 1);
                        int result = productQuoteMapper.save(entity.getId(), el.getProduct_id(), list.get(i), tmp);
                        Assert.isZero(result, "保存供应商报价信息失败:" + list.get(i));
                    }

                }
            });

        }


        return 1;
    }
}
